package logic

import (
	"cloud-disk/core/helper"
	"context"

	"cloud-disk/core/internal/svc"
	"cloud-disk/core/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserLoginLogic) UserLogin(req *types.LoginRequest) (resp *types.LoginResponse, err error) {
	resp = new(types.LoginResponse)
	user, err := l.svcCtx.UserModel.GetUserByNamePassword(req.Name, helper.Md5(req.Password))
	if err != nil {
		resp.Message = err.Error()
		resp.Code = 100
		return resp, nil
	}

	token, err := helper.GenerateToken(user.Id, user.Identity, user.Name, l.svcCtx.Config.TokenExpire)
	if err != nil {
		resp.Message = err.Error()
		resp.Code = 100
		return resp, nil
	}

	// 用户刷新用户认证token的token
	RefreshToken, err := helper.GenerateToken(user.Id, user.Identity, user.Name, l.svcCtx.Config.RefreshTokenExpire)
	if err != nil {
		resp.Message = err.Error()
		resp.Code = 100
		return resp, nil
	}

	resp.Token = token
	resp.Code = 200
	resp.Message = "登陆成功"
	resp.RefreshToken = RefreshToken
	return resp, nil
}
